import asyncio
from bleak import BleakClient

# 用于滑动的特征UUID，确认其真实有效
slide_characteristic_uuid = "00002b29-0000-1000-8000-00805f9b34fb"


async def slide_unlock(device_address, slide_direction):
    try:
        # 连接到 BLE 设备
        async with BleakClient(device_address) as client:
            if client.is_connected:
                # 发送滑动指令
                await client.write_gatt_char(slide_characteristic_uuid, slide_direction)
                print("Slide unlock command sent")
            else:
                print("Failed to connect to device")
    except Exception as e:
        print(f"Error during slide unlock: {e}")


async def discover_services_and_characteristics(device_address):
    try:
        # 连接到 BLE 设备
        async with BleakClient(device_address) as client:
            if client.is_connected:
                print(f"Connected to {device_address}")

                # 获取所有服务
                services = await client.get_services()
                for service in services:
                    print(f"Service: {service.uuid} - {service.description}")
                    # 获取每个服务的特征
                    for char in service.characteristics:
                        print(f"  Characteristic: {char.uuid} - {char.description} - {char.properties}")
            else:
                print("Failed to connect to device")
    except Exception as e:
        print(f"Error while discovering services: {e}")


# 主程序
async def main():
    device_address = "B8:EA:98:93:4C:71"
    slide_direction = bytes([0x01])  # 假设0x01代表向右滑动

    # 先发现服务和特征
    await discover_services_and_characteristics(device_address)

    # 然后发送滑动指令
    await slide_unlock(device_address, slide_direction)


# 运行异步主程序
loop = asyncio.get_event_loop()
loop.run_until_complete(main())